package service

import (
	"github.com/pkg/errors"
	"gorm.io/gorm"
	"zsc-boot/app/system_layer/model"
	"zsc-boot/app/system_layer/model/request"
	"zsc-boot/core/orm"
)

var ServiceDepartmentService = new(serviceDepartmentService)

type serviceDepartmentService struct {
}

// CreateDepartment 创建组织
func (s *serviceDepartmentService) CreateDepartment(department model.ServiceDepartment) (err error) {
	return orm.GetDb().Transaction(func(tx *gorm.DB) error {
		if err = tx.Create(&department).Error; err != nil {
			return err
		}

		return tx.Model(&model.ServiceUser{}).Where("id in ?", department.UserIds).
			Update("dep_id", department.ID).Error
	})
	//orm.GetDb().Model(&department).Association("DepartmentMembers").Append(department.DepartmentMembers)

}

// DeleteServiceDepartment 删除组织
// 新增 删除部门校验是否有员工和项目,如果有则提示"请先移除部门下所有员工和项目再进行删除部门操作"(在项目表和员工表通过部门ID查看数据)
func (s *serviceDepartmentService) DeleteServiceDepartment(department model.ServiceDepartment) (err error) {
	if err, department = s.GetServiceDepartment(department.ID); err != nil {
		return
	}

	if len(department.MembersList) > 0 {
		return errors.New("请先清空部门下的员工")
	}

	if len(department.Children) > 0 {
		return errors.New("请先清空子级部门")
	}

	err = orm.GetDb().Delete(&department).Error
	return
}

// UpdateServiceDepartment 更新组织
func (s *serviceDepartmentService) UpdateServiceDepartment(department model.ServiceDepartment) (err error) {
	return orm.GetDb().Transaction(func(tx *gorm.DB) error {
		//先清空部门下的员工
		if err = tx.Model(&model.ServiceUser{}).Where("dep_id = ?", department.ID).
			Update("dep_id", 0).Error; err != nil {
			return err
		}

		if err = tx.Updates(&department).Error; err != nil {
			return err
		}

		//修改
		return tx.Model(&model.ServiceUser{}).Where("id in ?", department.UserIds).
			Update("dep_id", department.ID).Error
	})

	//if err = orm.GetDb().Updates(&department).Error; err != nil {
	//	return err
	//}
	//if err = orm.GetDb().Model(&department).Association("DepartmentMembers").
	//	Replace(department.DepartmentMembers); err != nil {
	//	return err
	//}
	return
}

// GetServiceDepartment 获取组织详情
func (s *serviceDepartmentService) GetServiceDepartment(id uint) (err error, department model.ServiceDepartment) {
	err = orm.GetDb().Preload("PrincipalEmployees", "deleted_at is null").Preload("Children.Children.Children").
		Preload("MembersList").Where("id = ?", id).First(&department).Error
	return
}

// GetServiceDepartmentList 获取组织列表
func (s *serviceDepartmentService) GetServiceDepartmentList(info request.ServiceDepartmentSearch, userInfo model.ServiceUser) (
	err error, serviceDepartments []model.ServiceDepartment, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)

	db := orm.GetDb().Model(&model.ServiceDepartment{})
	if info.Name != "" {
		db.Where("name like ?", "%"+info.Name+"%")
	}
	if userInfo.Role.Code != "root" {
		db.Where("principal = ?", userInfo.ID)
	} else {
		if info.ParentId != nil {
			db.Where("parent_id = ?", info.ParentId)
		}
	}

	err = db.Count(&total).Error
	if err != nil {
		return
	}
	err = db.Preload("PrincipalEmployees").Preload("Children.Children").
		Preload("MembersList").Order("id desc").Limit(limit).Offset(offset).
		Find(&serviceDepartments).Error
	return err, serviceDepartments, total
}

func (s *serviceDepartmentService) GetDepUsers(deps []model.ServiceDepartment) (userList []model.ServiceUserSimple) {
	for _, dep := range deps {
		userList = append(userList, dep.MembersList...)
		if len(dep.Children) > 0 {
			userList = append(userList, s.GetDepUsers(dep.Children)...)
		}
	}
	return
}
